<template>
  <el-dialog
    v-model="isShow"
    :close-on-click-modal="false"
    title="发布公告"
    align="center"
    :show-close="false"
    draggable
  >
    <el-table :data="arrAllNameTel" style="width: 100%" height="200">
      <el-table-column type="index" width="50" />
      <el-table-column prop="name" label="小区名字" />
      <el-table-column prop="tel" label="物业电话" />
    </el-table>
    <el-form :model="notice" style="width: 100%">
      <el-form-item label="公告时间">
        <el-date-picker
          v-model="notice.time"
          type="datetime"
          placeholder="Pick a date"
          value-format="YYYY.MM.DD HH:mm"
          format="YYYY.MM.DD HH:mm"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="公告内容">
        <el-input
          v-model="notice.text"
          placeholder="请输入公告内容"
          clearable
          style="height: 50px"
          :autosize="{ minRows: 2, maxRows: 4 }"
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <el-button @click="onAddClick">确认发布</el-button>
    <el-button @click="onCloseClick" type="primary">关闭</el-button>
  </el-dialog>
</template>
<script setup>
import { defineExpose, getCurrentInstance, onMounted, ref } from "vue";
import { createDraw } from "@/zondyTools/ol-api/createDraw";
import {
  setLineStyle,
  setAreaStyle,
  FeatureToJSON,
  JSONToFeature,
} from "@/zondyTools/ol-api/index";
import { Query } from "@/zondyTools/mapgis-api/Query";
import { ElMessage } from "element-plus";
import { useNoticeStore } from "@/stores/notice";
const { addNotice } = useNoticeStore();
// 初始化
const arrAllNameTel = ref([]);
const notice = ref({ time: "", text: "" });
const isShow = ref(false);

// 地图要素数据
let $map = null;
let geoBuffer = null;
// 初始化地图数据
onMounted(() => {
  const { proxy } = getCurrentInstance();
  $map = proxy.$map;
  $map.addLayer(lineLayer);
});

/* 1.构建画布 */
// 线图层
let lineSource = new ol.source.Vector({});
let lineLayer = new ol.layer.Vector({
  source: lineSource,
  style: setLineStyle({}),
});
// 缓冲区图层
const bufferLayer = new ol.layer.Vector({
  source: new ol.source.Vector({
    features: [],
  }),
  style: new ol.style.Style({
    fill: new ol.style.Fill({
      color: "rgba(0, 0, 255, 0.5)", // 蓝色填充，50% 透明度
    }),
    stroke: new ol.style.Stroke({
      color: "blue",
      width: 2,
    }),
  }),
});
/* 2.构建线画笔 */
const lineDraw = createDraw({
  source: lineSource,
  type: "LineString",
});
const drawLine = () => {
  // 移除旧的交互
  $map.removeInteraction(lineDraw);
  // 添加新的交互
  $map.addInteraction(lineDraw);
  // 移除旧的监听器
  lineDraw.un("drawend", handleDrawEnd);
  // 添加新的监听器
  lineDraw.on("drawend", handleDrawEnd);
};
/* 涉及区域分析 */
const handleDrawEnd = (evt) => {
  // 移除画笔
  $map.removeInteraction(lineDraw);
  // 1. 获取线的几何信息,转化成GeoJSON格式
  const lineGeojson = FeatureToJSON(evt.feature);
  let { coordinates } = lineGeojson.geometry;
  // 2. 调用缓冲区分析服务
  const line = turf.lineString(coordinates);
  // 创建线的缓冲区，第二个参数是缓冲区的半径（单位是度）
  geoBuffer = turf.buffer(line, 0.1);
  console.log(geoBuffer);
  // geoBUffer 是geoJSON格式的缓冲区数据
  // 3. 将缓冲区的几何信息转化成OpenLayers的格式
  const olFeatures = new ol.format.GeoJSON().readFeatures(geoBuffer);
  // 4. 将缓冲区的OpenLayers格式添加到缓冲区图层中
  bufferLayer.getSource().clear();
  bufferLayer.getSource().addFeatures(olFeatures);

  // 检查 bufferLayer 是否已经在地图上
  if (!$map.getLayers().getArray().includes(bufferLayer)) {
    $map.addLayer(bufferLayer);
  }
  /* 叠加分析 bufferLayer和居民区 */
  const service = { name: "guanggu", layerId: 0 };
  Query.queryByLayerId({
    service,
    success: (res) => {
      let civilianArea = new ol.format.GeoJSON().writeFeaturesObject(res); // 居民区的geojson数据
      civilianArea.features.map((item) => {
        /* 将item 和 geoBuffer 转为turf格式 */

        //遍历每个居民区的图层来做拓扑
        const result = turf.booleanOverlap(item, geoBuffer);
        if (result) {
          // 给拓扑出来的区域加上属性值 处理数据  拿到最终结果
          let res = item.properties.values_;
          const { name, tel } = res;
          let obj = {};
          let propName = "name";
          let propTel = "tel";
          obj[propName] = name;
          obj[propTel] = tel;
          arrAllNameTel.value.push(obj); //最终数据
        }
      });
    },
  });
  // 打开面板
  isShow.value = true;
};
// 发布公告按钮
const onAddClick = () => {
  // 1. 获取公告信
  // 2. 发布公告
  // 3. 关闭面板
  addNotice(notice.value);
  onCloseClick();
};
// 关闭按钮
const onCloseClick = () => {
  arrAllNameTel.value = [];
  isShow.value = false;
  clearDraw();
};
const addAnnounceClick = () => {
  ElMessage.success("请开始绘制公告");
  drawLine();
};
// 清空画布
const clearDraw = () => {
  lineSource.clear();
  bufferLayer.getSource().clear(); // 清空缓冲区图层
};
defineExpose({ addAnnounceClick });
</script>
<style scoped>
.box {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 1px solid #ccc;
}
.el-form {
  padding: 10px;
  border-top: 1px solid #ccc;
}
</style>
